﻿'-------------------------------------------------------------------------------
'Developer: Ivan Tamurejo
'-------------------------------------------------------------------------------
'This module includes functions for processing INI files, encryption and 
'decryption of passwords and files with encoding Default reading.
'-------------------------------------------------------------------------------
Imports System.IO
Imports System.Text
Imports System.Reflection.Assembly

Public Module Auxiliary

#Region "Public variables"
    Public PathINI As String = Path.Combine(Path.GetDirectoryName(GetExecutingAssembly.Location), "RobotBuilds.ini")
#End Region

#Region "Private variables and Statements"

    'For use in functions GetSection(s)
    Private sBuffer As String

    '--- Statements to read INI files ---
    'Read all sections of an INI file, this certainly does not work in Win95
    Private Declare Function GetPrivateProfileSectionNames Lib "kernel32" Alias "GetPrivateProfileSectionNamesA" (ByVal lpszReturnBuffer As String, ByVal nSize As Integer, ByVal lpFileName As String) As Integer

    'Read a complete section
    Private Declare Function GetPrivateProfileSection Lib "kernel32" Alias "GetPrivateProfileSectionA" (ByVal lpAppName As String, ByVal lpReturnedString As String, ByVal nSize As Integer, ByVal lpFileName As String) As Integer

    'Read an INI file key
    Private Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Integer, ByVal lpFileName As String) As Integer
    Private Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Integer, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Integer, ByVal lpFileName As String) As Integer

    'Enter a key of an INI file (also to delete keys and sections)
    Private Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpString As String, ByVal lpFileName As String) As Integer
    Private Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpString As Integer, ByVal lpFileName As String) As Integer
    Private Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Integer, ByVal lpString As Integer, ByVal lpFileName As String) As Integer

#End Region

#Region "Functions and procedures for the processing of INI files"

    'Deleting a key or an INI file entry                  
    'Unless indicated sKey section indicated in sSection will be cleared
    'In another case, is supposed to be the (key) entry what you want to delete
    '
    'To delete a section IniDeleteSection should be used
    Public Sub IniDeleteKey(ByVal sIniFile As String, ByVal sSection As String, Optional ByVal sKey As String = "")


        If Len(sKey) = 0 Then
            'Delete a section
            Call WritePrivateProfileString(sSection, 0, 0, sIniFile)
        Else
            'Delete an entry
            Call WritePrivateProfileString(sSection, sKey, 0, sIniFile)
        End If
    End Sub

    'Delete a section of an INI file                          
    Public Sub IniDeleteSection(ByVal sIniFile As String, ByVal sSection As String)
        Call WritePrivateProfileString(sSection, 0, 0, sIniFile)
    End Sub


    'Returns the value of a key of an INI file
    'The parameters are:
    '   sFileName   INI file
    '   sSection    The section you want to read
    '   sKeyName    Key
    '   sDefault    Optional value that will be returned if the key is not
    Public Function IniGet(ByVal sFileName As String, ByVal sSection As String, ByVal sKeyName As String, Optional ByVal sDefault As String = "") As String
        Dim ret As Integer
        Dim sRetVal As String
        '
        sRetVal = New String(Chr(0), 255)
        '
        ret = GetPrivateProfileString(sSection, sKeyName, sDefault, sRetVal, Len(sRetVal), sFileName)
        If ret = 0 Then
            Return sDefault
        Else
            Return Left(sRetVal, ret)
        End If
    End Function

    'Saves the configuration data
    'Still sValue value to save
    Public Sub IniWrite(ByVal sFileName As String, ByVal sSection As String, ByVal sKeyName As String, ByVal sValue As String)
        Call WritePrivateProfileString(sSection, sKeyName, sValue, sFileName)
    End Sub



    'Reads an entire section of an INI file                    
    'Adapted to return an array of string                    
    '
    'This function will return an array of index zero
    'with the keys and values of the section
    '
    'Input parameters:
    '   sFileName   INI filename
    '   sSection    Name of the section to read
    'Returns:
    '   An array with the name of the key and value
    '   To read the data:
    '       For i = 0 To UBound(Array) -1 Step 2
    '           sKey = Array(i)
    '           sValue = Array(i+1)
    '       Next
    '
    Public Function IniGetSection(ByVal sFileName As String, ByVal sSection As String) As String()
        Dim aSeccion() As String
        Dim n As Integer
        '
        ReDim aSeccion(0)

        sBuffer = New String(ChrW(0), 32767)
        '
        n = GetPrivateProfileSection(sSection, sBuffer, sBuffer.Length, sFileName)
        '
        If n > 0 Then

            sBuffer = sBuffer.Substring(0, n - 2).TrimEnd()
            aSeccion = sBuffer.Split(New Char() {ChrW(0), "="c})
        End If

        Return aSeccion
    End Function

    '--------------------------------------------------------------------------
    'Returns all an INI file sections                
    'Adapted to return an array of string                  
    '
    'This function will return an array with all sections of the file
    '
    'Input parameters:
    '   sFileName   INI filename
    'Returns:
    'An array with all the names of sections
    'The first section will be in item 1, if the 
    'array contains zero elements is therefore that there is no sections
    Public Function IniGetSections(ByVal sFileName As String) As String()
        Dim n As Integer
        Dim aSections() As String
        '
        ReDim aSections(0)

        sBuffer = New String(ChrW(0), 32767)

        n = GetPrivateProfileSectionNames(sBuffer, sBuffer.Length, sFileName)
        '
        If n > 0 Then
            sBuffer = sBuffer.Substring(0, n - 2).TrimEnd()
            aSections = sBuffer.Split(ChrW(0))
        End If

        Return aSections
    End Function

#End Region

#Region "Encrypt/Decrypt strings"

    'This feature encrypts a string or decrypts according to the action, parameter that can
    'take the following values:
    '       E -----> Encrypt
    '       D -----> Decrypt   
    Public Function EncryptString(ByVal sString As String, ByVal sAction As String) As String

        'Password (Key) in this case we put a fixed always --->  ROBOTBUILDS
        Const vsPassword As String = "ROBOTBUILDS"

        Dim PasswordASCIIS() As Integer
        Dim CadenaASCIIS() As Integer

        Dim Temp As Integer
        Dim i As Integer
        Dim J As Integer
        Dim n As Integer
        Dim rtn As String

        rtn = ""

        EncryptString = ""

        Try

            'Get fixed password characters
            n = Len(vsPassword)
            ReDim PasswordASCIIS(0 To n + 1)
            For i = 1 To n
                PasswordASCIIS(i) = Asc(Mid(vsPassword, i, 1))
            Next

            'We get the characters in the string to encrypt or decrypt.
            ReDim CadenaASCIIS(Len(sString) - 1)
            For i = 0 To Len(sString) - 1
                CadenaASCIIS(i) = Asc(Mid(sString, i + 1, 1))
            Next

            'Encrypt/Decrypt
            If sAction = "E" Then 'Encrypt

                For i = 0 To Len(sString) - 1

                    J = CInt(IIf(J + 1 >= n, 0, J + 1))
                    Temp = CInt(CadenaASCIIS(i) + PasswordASCIIS(J))
                    If Temp > 255 Then
                        Temp = Temp - 255
                    End If
                    rtn = rtn + Chr(Temp)

                Next

            ElseIf sAction = "D" Then 'Decrypt

                For i = 0 To Len(sString) - 1

                    J = CInt(IIf(J + 1 >= n, 1, J + 1))
                    Temp = CadenaASCIIS(i) - PasswordASCIIS(J)
                    If Temp < 0 Then
                        Temp = Temp + 255
                    End If
                    rtn = rtn + Chr(Temp)

                Next

            End If

        Catch

            EncryptString = ""

        End Try

        'Return the value encrypted or unencrypted.
        EncryptString = rtn

        Return EncryptString

    End Function

#End Region

#Region "Reading files and strings with encoding Default"

    Public Function GetAllLinesFileEncondingDefault(ByVal sPathFile As String) As String()

        Dim oLineStream As StreamReader = Nothing
        Dim sLines As List(Of String) = Nothing

        Try

            oLineStream = New StreamReader(sPathFile, Encoding.Default)
            sLines = New List(Of String)

            Do While Not oLineStream.EndOfStream

                sLines.Add(oLineStream.ReadLine())

            Loop

            Return sLines.ToArray

        Catch

            Throw New Exception("> Failed to read file '" & sPathFile & "'.")

        Finally

            If Not oLineStream Is Nothing Then oLineStream.Dispose()
            sLines = Nothing

        End Try

    End Function

    Public Function GetAllTextFileEncondingDefault(ByVal sPathFile As String) As String

        Dim oLineStream As StreamReader = Nothing
        Dim sText As String = ""

        Try

            oLineStream = New StreamReader(sPathFile, Encoding.Default)
            sText = oLineStream.ReadToEnd

            Return sText

        Catch

            Throw New Exception("> Failed to read file '" & sPathFile & "'.")

        Finally

            If Not oLineStream Is Nothing Then oLineStream.Dispose()
            sText = Nothing

        End Try

    End Function

    Public Function GetStringEncodingDefault(ByVal sString As String) As String
        Dim bBytesIn() As Byte
        Dim bBytesOut() As Byte

        bBytesIn = Encoding.ASCII.GetBytes(sString)
        bBytesOut = Encoding.Convert(Encoding.UTF8, Encoding.Default, bBytesIn)

        Return Encoding.ASCII.GetString(bBytesOut)

    End Function

#End Region

#Region "Write in console"

    Public Sub WriteConsole(ByVal Message As String)

        Console.WriteLine(Message)

    End Sub

#End Region

End Module
